const ClassModel = require('../models/class.model');
const StudentModel = require('../models/student.model');
const CourseModel = require('../models/course.model');
const { v4: uuidv4 } = require('uuid');

exports.getClasses = async (req, res) => {
    try {
        const teacherId = req.user.id;
        const classes = await ClassModel.getClassesByTeacherId(teacherId);

        // 格式化返回数据
        const formattedClasses = classes.map(cls => ({
            id: cls.id,
            name: cls.name,
            studentCount: cls.studentCount, // 学生数量
            experimentCount: cls.experimentCount, // 实验数量
            status: cls.status,
            semester: cls.semester,
            courseCode: cls.courseCode,
            courseName: cls.courseName
        }));

        res.status(200).json({ classes: formattedClasses });
    } catch (error) {
        console.error('获取班级列表失败:', error);
        res.status(500).json({
            message: '获取班级列表失败',
            error: error.message
        });
    }
};

exports.createClass = async (req, res) => {
    let classId = null;
    let classCreated = false;
    let studentsProcessed = [];

    try {
        const teacherId = req.user.id;
        const {
            className,
            semester,
            courseCode,
            courseName,
            students
        } = req.body;

        // 检查或创建课程
        let course = await CourseModel.getCourseByCode(courseCode);
        if (!course) {
            course = await CourseModel.createCourse({
                courseCode,
                courseName,
                faculty: req.user.faculty || '计算机学院'
            });
        }

        // 检查班级是否已存在
        const existingClass = await ClassModel.getClassByNameAndTeacher(className, teacherId);
        if (existingClass) {
            return res.status(400).json({
                success: false,
                message: '班级已存在，请不要重复创建'
            });
        }

        // 创建班级
        classId = uuidv4();
        await ClassModel.createClass({
            id: classId,
            name: className,
            semester,
            teacherId,
            courseId: course.id,
            status: 'active'
        });
        classCreated = true;

        // 处理学生数据
        const studentIds = [];
        for (const student of students) {
            try {
                let studentRecord = await StudentModel.getStudentByNumber(student.studentId);

                if (!studentRecord) {
                    studentRecord = await StudentModel.createStudent({
                        s_no: student.studentId,
                        s_name: student.studentName,
                        class: student.className || className,
                    });
                }

                studentIds.push(studentRecord.id);
                studentsProcessed.push(studentRecord.id);
            } catch (studentError) {
                console.error(`处理学生 ${student.studentId} 失败:`, studentError);
                throw new Error(`添加学生失败: ${student.studentId}`);
            }
        }

        // 关联班级和学生
        await ClassModel.addStudentsToClass(classId, studentIds);

        res.status(201).json({
            success: true,
            message: '班级创建成功',
            classId,
            studentCount: students.length
        });

    } catch (error) {
        console.error('创建班级失败:', error);

        // 回滚处理
        if (classCreated) {
            try {
                await ClassModel.deleteClass(classId);
            } catch (rollbackError) {
                console.error('回滚操作失败:', rollbackError);
            }
        }

        res.status(500).json({
            success: false,
            message: '创建班级失败: ' + error.message
        });
    }
};

exports.addClassStudent = async (req, res) => {
    try {
        const { classId, students } = req.body; // 班级id和学生列表

        console.log("classId and students: ", classId, students);
        // 处理学生数据
        const studentIds = [];
        for (const student of students) {
            console.log("student: ", student);
            try {
                let studentRecord = await StudentModel.getStudentByNumber(student.s_no);
                console.log("studentRecord: ", studentRecord);
                if (!studentRecord) {
                    studentRecord = await StudentModel.createStudent({
                        s_no: student.s_no,
                        s_name: student.s_name,
                        class: student.class_name,
                    });
                }

                studentIds.push(studentRecord.id);
            } catch (studentError) {
                console.error(`处理学生 ${student.s_no} 失败:`, studentError);
                throw new Error(`添加学生失败: ${student.s_no}`);
            }
        }

        // 关联班级和学生
        await ClassModel.addStudentsToClass(classId, studentIds);

        res.status(201).json({
            success: true,
            message: '学生添加成功',
            classId,
            studentCount: students.length
        });

    } catch (error) {
        console.error('添加学生失败:', error);
        res.status(500).json({
            success: false,
            message: '添加学生失败: ' + error.message
        });
    }
};

exports.deleteClass = async (req, res) => {
    try {
        const classId = req.params.classId;
        await ClassModel.deleteClass(classId);
        res.status(200).json({
            success: true,
            message: '班级删除成功'
        });
    } catch (error) {
        console.error('删除班级失败:', error);
        res.status(500).json({
            success: false,
            message: '删除班级失败: ' + error.message
        });
    }
};

// 获取班级实验
exports.getClassExperiments = async (req, res) => {
    try {
        const classId = req.params.classId;
        const experiments = await ClassModel.getExpsForClass(classId);
        res.json(experiments);
    } catch (err) {
        console.error('获取班级实验失败:', err);
        res.status(500).json({ message: '获取班级实验失败' });
    }
};

// 获取班级学生列表
exports.getClassStudents = async (req, res) => {
    try {
        const classId = req.params.classId;
        const students = await ClassModel.getStudentsForClass(classId);
        res.json(students);
    } catch (err) {
        console.error('获取班级学生列表失败:', err);
        res.status(500).json({ message: '获取班级学生列表失败' });
    }
};

// 分配实验到班级
exports.assignExperimentToClass = async (req, res) => {
    try {
        const { classId, experimentId, deadline } = req.body;
        console.log("classId, experimentId, deadline: ", classId, experimentId, deadline);

        // 验证输入
        if (!classId || !experimentId || !deadline) {
            return res.status(400).json({
                success: false,
                message: '缺少必要参数：classId, experimentId, deadline'
            });
        }

        // 检查是否已分配
        const existingAssignment = await ClassModel.getExperimentAssignment(classId, experimentId);
        if (existingAssignment) {
            return res.status(400).json({
                success: false,
                message: '该实验已分配给此班级'
            });
        }

        // 创建分配
        await ClassModel.assignExperiment(classId, experimentId, deadline);

        res.status(201).json({
            success: true,
            message: '实验分配成功'
        });

    } catch (error) {
        console.error('分配实验失败:', error);
        res.status(500).json({
            success: false,
            message: '分配实验失败: ' + error.message
        });
    }
};

// 更新实验截止日期
exports.updateExperimentDeadline = async (req, res) => {
    try {
        const { classId, experimentId, deadline } = req.body;

        // 验证输入
        if (!classId || !experimentId || !deadline) {
            return res.status(400).json({
                success: false,
                message: '缺少必要参数：classId, experimentId, deadline'
            });
        }

        // 检查分配是否存在
        const assignment = await ClassModel.getExperimentAssignment(classId, experimentId);
        if (!assignment) {
            return res.status(404).json({
                success: false,
                message: '未找到该实验分配记录'
            });
        }

        // 更新截止日期
        await ClassModel.updateDeadline(classId, experimentId, deadline);

        res.status(200).json({
            success: true,
            message: '截止日期更新成功'
        });

    } catch (error) {
        console.error('更新截止日期失败:', error);
        res.status(500).json({
            success: false,
            message: '更新截止日期失败: ' + error.message
        });
    }
};

// 从班级移除实验
exports.removeExperimentFromClass = async (req, res) => {
    try {
        const classId = req.params.classId;
        const experimentId = req.params.experimentId;
        console.log("classId, experimentId: ", classId, experimentId);

        // 验证输入
        if (!classId || !experimentId) {
            return res.status(400).json({
                success: false,
                message: '缺少必要参数：classId, experimentId'
            });
        }

        // 检查分配是否存在
        const assignment = await ClassModel.getExperimentAssignment(classId, experimentId);
        if (!assignment) {
            return res.status(404).json({
                success: false,
                message: '未找到该实验分配记录'
            });
        }

        // 移除分配
        await ClassModel.removeExperiment(classId, experimentId);

        res.status(200).json({
            success: true,
            message: '实验移除成功'
        });

    } catch (error) {
        console.error('移除实验失败:', error);
        res.status(500).json({
            success: false,
            message: '移除实验失败: ' + error.message
        });
    }
};

exports.removeClassStudent = async (req, res) => {
    try {
        const classId = req.params.classId;
        const studentId = req.params.studentId;
        console.log("classId, studentId: ", classId, studentId);

        // 验证输入
        if (!classId || !studentId) {
            return res.status(400).json({
                success: false,
                message: '缺少必要参数：classId, studentId'
            });
        }
        // 移除学生
        await ClassModel.removeStudentFromClass(classId, studentId);

        res.status(200).json({
            success: true,
            message: '学生移除成功'
        });

    } catch (error) {
        console.error('移除学生失败:', error);
        res.status(500).json({
            success: false,
            message: '移除学生失败: ' + error.message
        });
    }
};